import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/init/diaodu_page.dart';
import 'package:jyofservice/init/repairer_page.dart';
import 'package:jyofservice/init/leader_page.dart';
import 'package:jyofservice/notice/NoticePage.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:mobpush_plugin/mobpush_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:jyofservice/bean/user_info_entity.dart';
import 'package:jyofservice/bean/work_condition_entity.dart';
import 'package:flutter/services.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'dart:io';
import 'dart:convert';
import 'package:jyofservice/msg/JpushMsg.dart';
import 'package:jyofservice/util/SlideRoute.dart';
import 'package:jyofservice/init/FunctionMenu.dart';
import '../util/MarqueeWidget.dart';
import 'Mine.dart';
import 'UpdatePage.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver{
  final GlobalKey<LeaderPageState> globalKeyLeader =
  GlobalKey<LeaderPageState>();
  final GlobalKey<RepairerPageState> globalKeyrepair =
  GlobalKey<RepairerPageState>();
  final GlobalKey<DiaoDuPageState> globalKey = GlobalKey<DiaoDuPageState>();
  final GlobalKey<FunctionMenuState> globalFunctionKey = GlobalKey<FunctionMenuState>();
  late SharedPreferences sharedPreferences;
  UserInfoEntity? userInfoEntity;
  String? key;
  List<WorkConditionEntity> posts = [];
  late Timer _timer;
  DateTime? _lastPressedAt;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    posts.clear();
    getUserInfo().then((onValue) {
      print("========${onValue}");
      if (onValue != null || onValue["Code"] == "200") {
        userInfoEntity = new UserInfoEntity.fromJson(onValue["Data"][0]);
        sharedPreferences.setInt("postid", userInfoEntity!.postId!);
        sharedPreferences.setInt("departmentid", userInfoEntity!.departmentId!);
        if(mounted){
          setState(() {
          });
        }
        getWorkCondition();
        //globalFunctionKey.currentState.getFunctionMenu();

      }
    });

    //添加推送回调监听（接收自定义透传消息回调、接收通知消息回调、接收点击通知消息回调）
    MobpushPlugin.addPushReceiver(_onEvent, _onError);

  }

  void _onEvent(Object? event) {
    print('推送回调_onEvent===$event');
    Map<String, dynamic> eventMap = json.decode(event as String);
    int? action = eventMap['action'];

    //action==1 前后台接收通知刷新 action==2点击通知跳转打开 应用程序可见，前台已做刷新,不需要重复执行
    if(action==1){
      _refresh();
    }

  }

  void _onError(Object? event) {
    print('推送回调_onError===$event');
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("--" + state.toString());
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed:// 应用程序可见，前台
      //刷新
        _refresh();
        break;
      case AppLifecycleState.paused: // 应用程序不可见，后台
        break;
      case AppLifecycleState.detached: // 申请将暂时暂停
        break;
      case AppLifecycleState.hidden:
        // TODO: Handle this case.
        break;
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    return UpdatePage(
        WillPopScope(
          onWillPop: () async{
            if(_lastPressedAt==null||DateTime.now().difference(_lastPressedAt!)>Duration(seconds: 2)) {
              //两次点击间隔超过1秒则重新计时
              _lastPressedAt = DateTime.now();
              Fluttertoast.showToast(msg: '连续按两次返回桌面');
              return false;
            }else{
              exit(0);
              _timer.cancel();
              return true;
            }
          },
          child: Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.white,
              centerTitle: true,
              title: Text(WebConfig().APPNAME,
                  style: TextStyle(
                      color: Colors.black, fontSize: ScreenUtil().setSp(45))),
              leading: TextButton(
                child: Icon(
                  Icons.message,
                  size: 30,
                ),
                onPressed: () {
//                NavigatorUtil.goJpushMsg(context);
                  Navigator.of(context).push(SlideRoute().createRoute(JpushMsg()));
                },
              ),
              actions: <Widget>[
                TextButton(
                  child: Icon(
                    Icons.person,
                    size: 30,
                  ),
                  onPressed: () {
                    Navigator.of(context)
                        .push(SlideRoute().createRoute(MinePage()));
                  },
                )
              ], systemOverlayStyle: SystemUiOverlayStyle.dark,
            ),
            body: RefreshIndicator(
                child: SingleChildScrollView(
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Container(
                          child: Image.asset(
                            'images/banner.png',
                            fit: BoxFit.fill,
                          ),
                          width: ScreenUtil().setWidth(750),
                          height: ScreenUtil().setHeight(400),
                        ),
                        Container(
                          color: const Color(0xFFF1F1F1),
                          padding: EdgeInsets.all(10),
                          child: Row(
                            children: <Widget>[
                              Text(
                                '运行工况',
                                style: TextStyle(
                                    color: Colors.blue,
                                    fontWeight: FontWeight.bold,
                                    fontStyle: FontStyle.italic,
                                    fontSize: ScreenUtil().setSp(35)),
                              ),
                              SizedBox(
                                width: ScreenUtil().setWidth(10),
                              ),
                              Container(
                                color: Colors.blue,
                                width: ScreenUtil().setWidth(2),
                                height: ScreenUtil().setHeight(30),
                              ),
                              SizedBox(
                                width: ScreenUtil().setWidth(10),
                              ),
                              Expanded(
                                  child: Container(
                                      height: ScreenUtil().setHeight(40),
                                      child: posts.length>0 ? MarqueeWidget(
                                        //子Item构建器
                                        itemBuilder: (BuildContext context, int index) {
                                          return Container(
                                            alignment: Alignment.centerLeft,
                                            child: Text(posts[index].title ?? '',
                                              style: TextStyle(
                                                  color: Colors.blue,
                                                  fontSize: ScreenUtil().setSp(30)),
                                            ),
                                          );
                                        },
                                        //循环的提示消息数量工作总时差最小的工作
                                        count:  posts.length>3?3:posts.length,
                                      ):Container()
                                  )),
                              GestureDetector(
                                onTap: () {
                                  Navigator.of(context)
                                      .push(SlideRoute().createRoute(NoticePage()));
                                },
                                child: Text(
                                  '更多...',
                                  style: TextStyle(
                                      color: Colors.blue,
                                      fontSize: ScreenUtil().setSp(28)),
                                ),
                              )
                            ],
                          ),
                        ),
                        FunctionMenu(key:globalFunctionKey),
                        Container(
                          color: const Color(0xFFF1F1F1),
                          height: ScreenUtil().setHeight(20),
                        ),
                        getMainPage(),
//              LeaderPage(),
                      ],
                    ),
                  ),
                ),
                onRefresh: _refresh),
          ),
        )

    );
  }
  Future _refresh() async{
    if (userInfoEntity != null) {
      switch (userInfoEntity!.postId) {
        case 1: //客服主管领导
          globalKeyLeader.currentState?.getStaticNum();
          break;
        case 2: //客服人员
          globalKeyLeader.currentState?.getStaticNum();
          break;
        case 3:
          globalKey.currentState?.getStaticNum();
          // globalKey.currentState.getDiaoDuListData();
          break;
        case 4:
          globalKeyrepair.currentState?.getStaticNum();
          // globalKeyrepair.currentState.getWoDeListData();
          break;
      }
    }
    getWorkCondition();
    globalFunctionKey.currentState!.getFunctionMenu();
  }
  List<DataRow> getTableRow() {
    List<DataRow> list = [];
    for (int i = 0; i < posts.length; i++) {
      list.add(DataRow(cells: [
        DataCell(Text(
          posts[i].title ?? '',
          style: TextStyle(fontSize: ScreenUtil().setSp(30)),
        )),
        DataCell(Text(
          posts[i].neiRong ?? '',
          style: TextStyle(fontSize: ScreenUtil().setSp(30)),
        )),
        DataCell(Text(
          posts[i].fanWeiName ?? '',
          style: TextStyle(fontSize: ScreenUtil().setSp(30)),
        )),
        DataCell(Text(
          posts[i].endDt ?? '',
          style: TextStyle(fontSize: ScreenUtil().setSp(30)),
        )),
        DataCell(Text(
          posts[i].createDate ?? '',
          style: TextStyle(fontSize: ScreenUtil().setSp(30)),
        )),
        DataCell(Text(
          posts[i].realName ?? '',
          style: TextStyle(fontSize: ScreenUtil().setSp(30)),
        )),
      ]));
    }
    print(list.length);
    return list;
  }

  Widget getMainPage() {
    if (userInfoEntity != null) {
      switch (userInfoEntity!.postId) {
        case 1: //客服主管领导
          return LeaderPage(key: globalKeyLeader);
        case 2: //客服人员
          return LeaderPage(key: globalKeyLeader);
        case 3:
          return DiaoDuPage(key: globalKey);
        case 4:
          return RepairerPage(key: globalKeyrepair);
        default:
          return Container();
      }
    } else {
      return Container();
    }
  }


  Future getUserInfo() async {
    sharedPreferences = await SharedPreferences.getInstance();
    key = sharedPreferences.getString("key");
    String aesData= await (AesUtil.encodeBase64());
    var data = {"key": key,"ClientType":"phone","ClientKey":aesData};
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getuserinfo",
        data: data);
    return response.data;
  }

  Future getWorkCondition() async {
    posts.clear();
    String aesData= await AesUtil.encodeBase64();
    var data = {"key": key,"ClientType":"phone","ClientKey":aesData};
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/GetMyDepartmentWorkInfo",
        data: data);
    if (mounted) {
      setState(() {
        for (int i = 0; i < response.data["Data"].length; i++) {
          posts.add(new WorkConditionEntity.fromJson(response.data["Data"][i]));
        }
      });
    }

    return response.data;
  }
}
